<?php

namespace app\teacher\controller\learn;

use app\common\controller\Frontend;
use app\common\enums\LearnMeansEnum;
use app\common\enums\LearnSubjectAntiForgettingStatusEnum;
use app\common\model\banxi\learn\LearnSkRecord as LearnSkRecordModel;
use app\common\model\banxi\learn\LearnSubjectAntiForgetting as LearnSubjectAntiForgettingModel;
use app\common\model\banxi\learn\LearnSubjectQuestionRecord;
use think\facade\Log;

/*
 * 全科抗遗忘
 * */
class LearnSubjectAntiForgetting extends Frontend
{
    protected array $noNeedLogin = [''];

    protected array $noNeedPermission = ['*'];

    public function initialize(): void
    {
        parent::initialize();
    }

    /*
     * 创建抗遗忘
     * */
    public function createSubjectAntiForgetting()
    {
        $skRecordId = $this->request->post('skRecordId', 0);
        $time = $this->request->post('time', '');

        // 根据预约ID查询上课记录
        $LearnSkRecordModel = new LearnSkRecordModel();
        $learnSkRecord = $LearnSkRecordModel
            ->where('id', $skRecordId)
            ->find();
        if (!$learnSkRecord) {
            $this->fail('请选择要创建的课程');
        }
        if(!$time){
            $this->fail('请选择时间');
        }
        $LearnSubjectAntiForgettingModel = new LearnSubjectAntiForgettingModel();

        $trainerId = $this->auth->id;

        // 检查是否已经为该上课记录创建过抗遗忘记录
        $exists = $LearnSubjectAntiForgettingModel
            ->where('skRecordId', $skRecordId)
            ->find();
        if ($exists) {
            $this->fail('该课程已创建抗遗忘记录');
        }

        // 构造数据创建从明天开始算连续5天的抗遗忘记录
        $records = [];
        for ($i = 1; $i <= 5; $i++) {
            $date = date('Y-m-d', strtotime("+$i day"));
            $records[] = [
                'title' => $learnSkRecord['courseName'],
                'trainerAntiForgettingId' => $learnSkRecord['trainerId'],
                'skRecordId' => $skRecordId,
                'studentId' => $learnSkRecord['studentId'],
                'studentOrgId' => $learnSkRecord['studentOrgId'],
                'date' => $date,
                'time' => $time,
                'courseId' => $learnSkRecord['courseId']
            ];
        }

        // 批量插入数据
        try {
            $LearnSubjectAntiForgettingModel->saveAll($records);
            //更新上课记录
            $learnSkRecord->isCreateAntiForgetting = 1;
            $learnSkRecord->save();
        } catch (\Exception $e) {
            Log::error('创建抗遗忘记录失败: ' . $e->getMessage());
            $this->fail('创建失败');
        }

        $this->ok('操作成功');
    }


    /**
     * 查询-我的抗遗忘记录
     *
     * @return \think\response\Json
     */
    public function listMyList()
    {
        // 获取当前用户ID
        $trainerId = $this->auth->id;

        // 查询符合条件的抗遗忘记录（日期大于等于今天）
        $LearnSubjectAntiForgettingModel = new LearnSubjectAntiForgettingModel();
        $trainerList = $LearnSubjectAntiForgettingModel
            ->with(['studentInfo','skRecord'])
            ->where('trainerAntiForgettingId', $trainerId)
            ->where('date', '>=', date('Y-m-d')) // 日期大于等于今天
            ->select();

        // 按日期分组包装结果
        $result = $LearnSubjectAntiForgettingModel->wrapperReviewDate($trainerList);

        $this->ok('操作成功', $result);
    }

    /*
     * 开始抗遗忘
     * */
    public function startAntiForgetting()
    {
        $id = $this->request->post('id', 0);

        $LearnSubjectAntiForgettingModel = new LearnSubjectAntiForgettingModel();

        $trainerId = $this->auth->id;

        $record = $LearnSubjectAntiForgettingModel
            ->where(['id'=>$id,'trainerAntiForgettingId'=>$trainerId])
            ->find();
        if (!$record) {
            $this->fail('抗遗忘记录不存在');
        }
        if ($record['status'] != LearnSubjectAntiForgettingStatusEnum::E1){
            $this->fail('抗遗忘状态有误');
        }
        if ($record['date'] != date('Y-m-d')){
            $this->fail('未到抗遗忘时间');
        }
        $record->status = LearnSubjectAntiForgettingStatusEnum::E2;
        $record->save();

        $this->ok('操作成功');
    }

    /*
     * 结束抗遗忘
     * */
    public function endAntiForgetting()
    {
        $id = $this->request->post('id', 0);

        $LearnSubjectAntiForgettingModel = new LearnSubjectAntiForgettingModel();

        $trainerId = $this->auth->id;

        $record = $LearnSubjectAntiForgettingModel
            ->where(['id'=>$id,'trainerAntiForgettingId'=>$trainerId])
            ->find();
        if (!$record) {
            $this->fail('抗遗忘记录不存在');
        }
        if ($record['status'] != LearnSubjectAntiForgettingStatusEnum::E2){
            $this->fail('抗遗忘状态有误');
        }

        $record->status = LearnSubjectAntiForgettingStatusEnum::E3;
        $record->save();

        $this->ok('操作成功');
    }

    /*
     * 查询-学习报告
     * */
    public function getLearningReport()
    {
        $id = $this->request->get('id');
        $LearnSubjectAntiForgettingModel = new LearnSubjectAntiForgettingModel();
        $record = $LearnSubjectAntiForgettingModel
            ->where(['id'=>$id])
            ->find();
        if (!$record) {
            $this->fail('抗遗忘记录不存在');
        }
        $LearnSkRecordModel = new LearnSkRecordModel();
        // 获取学习报告数据
        $learningReport = $LearnSkRecordModel->with([
            'studentInfo',
            'accountClassHour'
        ])->find($record['skRecordId']);
        //初始化全科练习数据
        $learningReport['inSubjectQuestion'] = [
            'questionNum' => 0,
            'rightRate' => 0
        ];
        $learningReport['afterSubjectQuestion'] = [
            'questionNum' => 0,
            'rightRate' => 0
        ];
        $LearnSubjectQuestionRecordModel = new LearnSubjectQuestionRecord();
        //全科随堂练习数据
        $in_subject_question_record = $LearnSubjectQuestionRecordModel->where(['subjectAntiForgettingId'=>$id,'learnMeans'=>LearnMeansEnum::E3,'exerciseType'=>2])->find();
        if ($in_subject_question_record){
            $learningReport['inSubjectQuestion'] = [
                'questionNum' => $in_subject_question_record['totalNum'],
                'rightRate' => $in_subject_question_record['rightRate']
            ];
        }
        //全科课后作业数据
        $after_subject_question_record = $LearnSubjectQuestionRecordModel->where(['subjectAntiForgettingId'=>$id,'learnMeans'=>LearnMeansEnum::E3,'exerciseType'=>3])->find();
        if ($after_subject_question_record){
            $learningReport['afterSubjectQuestion'] = [
                'questionNum' => $after_subject_question_record['totalNum'],
                'rightRate' => $after_subject_question_record['rightRate']
            ];
        }

        $this->ok('操作成功', $learningReport);
    }
}